package cn.powertime.evaluation.app.controller;

import cn.powertime.evaluation.Constants;
import cn.powertime.evaluation.entity.*;
import cn.powertime.evaluation.service.*;
import cn.powertime.evaluation.shiro.ShiroUtils;
import cn.powertime.evaluation.vo.*;
import cn.powertime.evaluation.web.controller.BaseController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.powertime.id.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/app/search")
@Api(value = "/app/search", tags = "搜索接口", produces = MediaType.ALL_VALUE)
public class AppCpsSearchController extends BaseController {

    @Autowired
    private CpsHotSearchService cpsHotSearchService;

    @Autowired
    private CpsSearchHistoryService cpsSearchHistoryService;

    @Autowired
    private DbqQuestionService dbqQuestionService;

    @Autowired
    private CpsChapterService cpsChapterService;

    @Autowired
    private CpsKnowledgeBaseService cpsKnowledgeBaseService;

    @Autowired
    private DbqAnswerService dbqAnswerService;

    @Autowired
    private  DbqPostingsCommentService dbqPostingsCommentService;


    @Autowired
    private CpsUserLearningRecordService cpsUserLearningRecordService;

    @Autowired
    private  SysUserService sysUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/hotSearch")
    @ApiOperation(value = "热门搜索",response = CpsHotSearch.class)
    public Object  hotSearch(){
        PageHelper.startPage(1,12);
        QueryWrapper<CpsHotSearch> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", Constants.ALLOW_DEL);
        queryWrapper.orderByAsc("pv");
        List<CpsHotSearch> cpsHotSearches=cpsHotSearchService.list(queryWrapper);
        return  success(cpsHotSearches);
    }

    @PostMapping("/historySearch")
    @ApiOperation(value = "历史搜索")
    public Object historySearch(){

        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        Long id=userInfo.getId();
        QueryWrapper<CpsSearchHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", Constants.STATUS_NORMAL);
        queryWrapper.eq("user_id",userInfo.getId());
        //queryWrapper.eq("user_id",1);
        queryWrapper.orderByAsc("create_time");
        PageHelper.startPage(1,12);
        List<CpsSearchHistory> list=cpsSearchHistoryService.list(queryWrapper);
        return  success(list);
    }

    @PostMapping("/historyDelete")
    @ApiOperation(value = "清空历史搜索")
    public Object  historyDelete(){
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        Long id=userInfo.getId();
        //cpsSearchHistory.setId(userInfo.getId());

        boolean b=cpsSearchHistoryService.batch(id);
        if (b) {
            return success("成功");
        }
        return  error("失败");
    }

    @PostMapping("/historyTitle")
    @ApiOperation(value = "搜索内容")
    public Object searchTitle(@Validated @RequestBody CpsSearchVo cpsSearchVo){
        Map<String,Object> map= new HashMap<>();
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        String  WebRespCourseAllListVo = stringRedisTemplate.opsForValue().get(userInfo.getId() + "-course");
        List<WebChapterVo> list = new ArrayList<>();
        List<WebChapterVoS> list6=new ArrayList<>();
        if ( WebRespCourseAllListVo != null) {
            Long courseId = Long.parseLong(WebRespCourseAllListVo);
                cpsSearchVo.setId(courseId);
                 cpsSearchVo.setUserId(userInfo.getId());
                 list=cpsChapterService.chapterSearchLists(cpsSearchVo);
            Double dd;
            for(int i=0;i<list.size();i++){
                WebChapterVoS webChapterVoS = new WebChapterVoS();
                Long resourcesize =list.get(i).getResourcesize();
                Double  schedule=list.get(i).getSchedule();
                if(schedule==null){
                    dd=0.00;
                }else {
                    dd = schedule/(resourcesize * 1.0);
                }
                BigDecimal bg = new BigDecimal(dd);
                Double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                if(f1>1.00){
                    f1=1.00;
                }
                webChapterVoS.setChapterfileid(list.get(i).getChapterfileid());
                webChapterVoS.setChapterName(list.get(i).getChapterName());
                webChapterVoS.setCoursefileid(list.get(i).getCoursefileid());
                webChapterVoS.setCourseName(list.get(i).getCourseName());
                webChapterVoS.setFileId(list.get(i).getFileId());
                webChapterVoS.setId(list.get(i).getId());
                webChapterVoS.setPid(list.get(i).getPid());
                webChapterVoS.setSchedule(schedule);
                webChapterVoS.setResourcesize(list.get(i).getResourcesize());
                webChapterVoS.setCourseId(list.get(i).getCourseId());
                webChapterVoS.setPercentage(f1);
                webChapterVoS.setDes(list.get(i).getDes());
                webChapterVoS.setIntroduce(list.get(i).getIntroduce());
                webChapterVoS.setCredit(list.get(i).getCredit());
                webChapterVoS.setPosition(list.get(i).getPosition());
                list6.add(webChapterVoS);
            }
            //}
        }
        map.put("chapter",list6);
        //cpsSearchVo.setId(userInfo.getId());
        cpsSearchVo.setId(1L);
        List<DbqQuestionVo> list1=dbqQuestionService.questionSearchList(cpsSearchVo);
        List<DbqQuestionListVo> questionVoSList = new ArrayList<>();
        DbqQuestionListVo dbqQuestionListVo;
        if(list1.size()>0){
            for(int i=0;i<list1.size();i++){
                QueryWrapper<DbqAnswer> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("status", Constants.STATUS_NORMAL);
                queryWrapper.eq("question_id",list1.get(i).getId());
                int s=dbqAnswerService.count(queryWrapper);
                dbqQuestionListVo = new DbqQuestionListVo();
                dbqQuestionListVo.setContent(list1.get(i).getContent());
                dbqQuestionListVo.setCount(s);
                dbqQuestionListVo.setId(list1.get(i).getId());
                dbqQuestionListVo.setTitle(list1.get(i).getTitle());
                dbqQuestionListVo.setUserId(userInfo.getId());
                //dbqQuestionListVo.setUserId(1L);
                dbqQuestionListVo.setNickName(list1.get(i).getNickName());
                dbqQuestionListVo.setClassifiedGade(list1.get(i).getClassifiedGade());
                dbqQuestionListVo.setAvatar(list1.get(i).getAvatar());
                dbqQuestionListVo.setFileId(list1.get(i).getFileId());
                dbqQuestionListVo.setNewsWarePv(list1.get(i).getScore());
                dbqQuestionListVo.setCreateTime(list1.get(i).getCreateTime());
                dbqQuestionListVo.setFileId(list1.get(i).getFileId());
                questionVoSList.add(dbqQuestionListVo);
            }
        }
        map.put("question",questionVoSList);
        List<KnowledgeSearchsVo> list2 =cpsKnowledgeBaseService.knowledgeSearchs(cpsSearchVo);
        List<KnowledgeSearchsVos> knowledgeSearchsVosList = new ArrayList<>();
        KnowledgeSearchsVos knowledgeSearchsVos;
        if(list2.size()>0){
            for(int i=0;i<list2.size();i++){
                knowledgeSearchsVos= new KnowledgeSearchsVos();
                QueryWrapper<DbqPostingsComment> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("status", Constants.STATUS_NORMAL);
                queryWrapper.eq("knowledge_id",list2.get(i).getId());
                int s=dbqPostingsCommentService.count(queryWrapper);
                QueryWrapper<SysUser> queryWrapper1= new QueryWrapper<>();
                queryWrapper1.eq("id",list2.get(i).getUserId());
                List<SysUser> sysUsers=sysUserService.list(queryWrapper1);
                knowledgeSearchsVos.setContent(list2.get(i).getContent());
                knowledgeSearchsVos.setCommentCount(s);
                knowledgeSearchsVos.setFields(list2.get(i).getFields());
                knowledgeSearchsVos.setFileId(list2.get(i).getFileId());
                knowledgeSearchsVos.setId(list2.get(i).getId());
                knowledgeSearchsVos.setNickname(sysUsers.get(0).getNickname());
                knowledgeSearchsVos.setNewsWarePv(list2.get(i).getReceptionNumber());
                knowledgeSearchsVos.setReleaseDate(list2.get(i).getReleaseDate());
                knowledgeSearchsVos.setTitle(list2.get(i).getTitle());
                knowledgeSearchsVos.setType(list2.get(i).getType());
                if(sysUsers.get(0).getAvatar()==null){
                    knowledgeSearchsVos.setAvatar(list2.get(i).getAvatar());
                }else {
                    knowledgeSearchsVos.setAvatar(sysUsers.get(0).getAvatar().toString());
                }
                knowledgeSearchsVosList.add(knowledgeSearchsVos);
            }
        }

        map.put("knowledge",knowledgeSearchsVosList);
        QueryWrapper<CpsSearchHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", Constants.STATUS_NORMAL);
        queryWrapper.eq("user_id",userInfo.getId());
       // queryWrapper.eq("user_id",1L);
        queryWrapper.eq("title",cpsSearchVo.getTitle());
        List<CpsSearchHistory> list3=cpsSearchHistoryService.list(queryWrapper);
        if(list3.size()>0){
              CpsSearchHistory cpsSearchHistory=list3.get(0);
              cpsSearchHistory.setUpdateTime(LocalDateTime.now());
              boolean b=cpsSearchHistoryService.ownUpdateById( cpsSearchHistory);
              if(!b){
                  return  error("增加历史搜索失败");
              }
        }else {
            CpsSearchHistory cpsSearchHistory=new CpsSearchHistory();
            cpsSearchHistory.setId(IdWorker.getId());
            cpsSearchHistory.setStatus(Constants.STATUS_CREDIT);
            cpsSearchHistory.setTitle(cpsSearchVo.getTitle());
            cpsSearchHistory.setUserId(userInfo.getId());
            //cpsSearchHistory.setUserId(1L);
            cpsSearchHistory.setUpdateTime(LocalDateTime.now());
            cpsSearchHistory.setUpdateTime(LocalDateTime.now());
            boolean b=cpsSearchHistoryService.ownSave( cpsSearchHistory);
            if(!b){
                return  error("增加历史搜索失败");
            }
        }
        QueryWrapper<CpsHotSearch> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("status", Constants.STATUS_NORMAL);
        queryWrapper1.eq("title",cpsSearchVo.getTitle());
        List<CpsHotSearch>  cpsHotSearches=cpsHotSearchService.list(queryWrapper1);
        if (cpsHotSearches.size()>0){
            CpsHotSearch cpsHotSearch =cpsHotSearches.get(0);
            Long pv=cpsHotSearch.getPv();
            cpsHotSearch.setPv(pv++);
            boolean b1=cpsHotSearchService.ownUpdateById(cpsHotSearch);
            if(!b1){
                return  error("增加热门搜索失败");
            }
        }else {
            CpsHotSearch cpsHotSearch = new CpsHotSearch();
            cpsHotSearch.setId(IdWorker.getId());
            cpsHotSearch.setPv(1L);
            cpsHotSearch.setStatus(Constants.STATUS_CREDIT);
            cpsHotSearch.setTitle(cpsSearchVo.getTitle());
            cpsHotSearch.setCreateTime(LocalDateTime.now());
            cpsHotSearch.setUpdateTime(LocalDateTime.now());
            boolean b1=cpsHotSearchService.ownSave(cpsHotSearch);
            if(!b1){
                return  error("增加热门搜索失败");
            }
        }
        return success2(map,cpsSearchVo.getTitle());
    }


    @PostMapping("/historyDetailed")
    @ApiOperation(value = "搜索内容详情")
    public Object searchDetailed(@Validated @RequestBody SearchDetailedVo vo){
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        if(vo.getType()==1){
            String  WebRespCourseAllListVo = stringRedisTemplate.opsForValue().get(userInfo.getId() + "-course");
            List<WebChapterVo> list = new ArrayList<>();
            List<WebChapterVoS> list1=new ArrayList<>();
            Long total=0L;
            if ( WebRespCourseAllListVo != null) {
                Long courseId = Long.parseLong(WebRespCourseAllListVo);
                CpsSearchVo cpsSearchVo= new CpsSearchVo();
                cpsSearchVo.setTitle(vo.getTitle());
                cpsSearchVo.setId(courseId);
                cpsSearchVo.setUserId(userInfo.getId());
                Page page= PageHelper.startPage(vo.getPage(),vo.getSize());
                list=cpsChapterService.chapterSearchLists(cpsSearchVo);
                 total=page.getTotal();
            }
            Double dd;
            for(int i=0;i<list.size();i++){
                WebChapterVoS webChapterVoS = new WebChapterVoS();
                Long resourcesize =list.get(i).getResourcesize();
                Double  schedule=list.get(i).getSchedule();
                if(schedule==null){
                    dd=0.00;
                }else {
                    dd = schedule/(resourcesize * 1.0);
                }
                BigDecimal bg = new BigDecimal(dd);
                Double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                if(f1>1.00){
                    f1=1.00;
                }
                webChapterVoS.setChapterfileid(list.get(i).getChapterfileid());
                webChapterVoS.setChapterName(list.get(i).getChapterName());
                webChapterVoS.setCoursefileid(list.get(i).getCoursefileid());
                webChapterVoS.setCourseName(list.get(i).getCourseName());
                webChapterVoS.setFileId(list.get(i).getFileId());
                webChapterVoS.setId(list.get(i).getId());
                webChapterVoS.setPid(list.get(i).getPid());
                webChapterVoS.setResourcesize(list.get(i).getResourcesize());
                webChapterVoS.setSchedule(schedule);
                webChapterVoS.setCourseId(list.get(i).getCourseId());
                webChapterVoS.setPercentage(f1);
                webChapterVoS.setDes(list.get(i).getDes());
                webChapterVoS.setIntroduce(list.get(i).getIntroduce());
                webChapterVoS.setCredit(list.get(i).getCredit());
                webChapterVoS.setPosition(list.get(i).getPosition());
                list1.add(webChapterVoS);
            }
            PageInfo pageInfo = new PageInfo(list1);
            return success1(list1,pageInfo.getPages(),pageInfo.getPageSize(),total);
        }

        if(vo.getType()==3){
            CpsSearchVo cpsSearchVo1= new CpsSearchVo();
            cpsSearchVo1.setTitle(vo.getTitle());
            cpsSearchVo1.setId(1L);
            //cpsSearchVo.setId(userInfo.getId());
            Page page1= PageHelper.startPage(vo.getPage(),vo.getSize());
            List<DbqQuestionVo> list1=dbqQuestionService.questionSearchList(cpsSearchVo1);
            List<DbqQuestionListVo> questionVoSList = new ArrayList<>();
            //WebChapterVoS webChapterVoS;
            DbqQuestionListVo dbqQuestionListVo;
            double dd;
            if(list1.size()>0){
                for(int i=0;i<list1.size();i++){
                    QueryWrapper<DbqAnswer> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("status", Constants.STATUS_NORMAL);
                    queryWrapper.eq("question_id",list1.get(i).getId());
                    int s=dbqAnswerService.count(queryWrapper);
                    dbqQuestionListVo = new DbqQuestionListVo();
                    dbqQuestionListVo.setContent(list1.get(i).getContent());
                    dbqQuestionListVo.setCount(s);
                    dbqQuestionListVo.setId(list1.get(i).getId());
                    dbqQuestionListVo.setTitle(list1.get(i).getTitle());
                    dbqQuestionListVo.setUserId(userInfo.getId());
                    //dbqQuestionListVo.setUserId(1L);
                    dbqQuestionListVo.setNickName(list1.get(i).getNickName());
                    dbqQuestionListVo.setClassifiedGade(list1.get(i).getClassifiedGade());
                    dbqQuestionListVo.setAvatar(list1.get(i).getAvatar());
                    dbqQuestionListVo.setFileId(list1.get(i).getFileId());
                    dbqQuestionListVo.setNewsWarePv(list1.get(i).getScore());
                    dbqQuestionListVo.setCreateTime(list1.get(i).getCreateTime());
                    dbqQuestionListVo.setFileId(list1.get(i).getFileId());
                    questionVoSList.add(dbqQuestionListVo);

                }
            }
            PageInfo pageInfo = new PageInfo( questionVoSList);
            return success1(questionVoSList,pageInfo.getPages(),pageInfo.getPageSize(), page1.getTotal());
        }

        if(vo.getType()==2){
            CpsSearchVo cpsSearchVo1= new CpsSearchVo();
            cpsSearchVo1.setTitle(vo.getTitle());
            cpsSearchVo1.setId(1L);
            Page page2= PageHelper.startPage(vo.getPage(),vo.getSize());
            List<KnowledgeSearchsVo> list2 =cpsKnowledgeBaseService.knowledgeSearchs(cpsSearchVo1);
            List<KnowledgeSearchsVos> knowledgeSearchsVosList = new ArrayList<>();
            KnowledgeSearchsVos knowledgeSearchsVos;
            if(list2.size()>0){
                for(int i=0;i<list2.size();i++){
                    knowledgeSearchsVos= new KnowledgeSearchsVos();
                    QueryWrapper<DbqPostingsComment> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("status", Constants.STATUS_NORMAL);
                    queryWrapper.eq("knowledge_id",list2.get(i).getId());
                    int s=dbqPostingsCommentService.count(queryWrapper);
                    QueryWrapper<SysUser> queryWrapper1= new QueryWrapper<>();
                    queryWrapper1.eq("id",list2.get(i).getUserId());
                    List<SysUser> sysUsers=sysUserService.list(queryWrapper1);
                    knowledgeSearchsVos.setContent(list2.get(i).getContent());
                    knowledgeSearchsVos.setCommentCount(s);
                    knowledgeSearchsVos.setFields(list2.get(i).getFields());
                    knowledgeSearchsVos.setFileId(list2.get(i).getFileId());
                    knowledgeSearchsVos.setId(list2.get(i).getId());
                    knowledgeSearchsVos.setNickname(list2.get(i).getNickname());
                    knowledgeSearchsVos.setNewsWarePv(list2.get(i).getReceptionNumber());
                    knowledgeSearchsVos.setReleaseDate(list2.get(i).getReleaseDate());
                    knowledgeSearchsVos.setTitle(list2.get(i).getTitle());
                    knowledgeSearchsVos.setType(list2.get(i).getType());
                    if(sysUsers.get(0).getAvatar()==null){
                        knowledgeSearchsVos.setAvatar(list2.get(i).getAvatar());
                    }else {
                        knowledgeSearchsVos.setAvatar(sysUsers.get(0).getAvatar().toString());
                    }
                    knowledgeSearchsVosList.add(knowledgeSearchsVos);

                }
            }
            PageInfo pageInfo = new PageInfo( knowledgeSearchsVosList);
            return success1(knowledgeSearchsVosList,pageInfo.getPages(),pageInfo.getPageSize(), page2.getTotal());
        }
        QueryWrapper<CpsSearchHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", Constants.STATUS_NORMAL);
        queryWrapper.eq("user_id",userInfo.getId());
        //queryWrapper.eq("user_id",1L);
        queryWrapper.eq("title",vo.getTitle());
        List<CpsSearchHistory> list3=cpsSearchHistoryService.list(queryWrapper);
        if(list3.size()>0){
            CpsSearchHistory cpsSearchHistory=list3.get(0);
            cpsSearchHistory.setUpdateTime(LocalDateTime.now());
            boolean b=cpsSearchHistoryService.ownUpdateById( cpsSearchHistory);
            if(!b){
                return  error("增加历史搜索失败");
            }
        }else {
            CpsSearchHistory cpsSearchHistory=new CpsSearchHistory();
            cpsSearchHistory.setId(IdWorker.getId());
            cpsSearchHistory.setStatus(Constants.STATUS_CREDIT);
            cpsSearchHistory.setTitle(vo.getTitle());
            cpsSearchHistory.setUserId(userInfo.getId());
            //cpsSearchHistory.setUserId(1L);
            cpsSearchHistory.setUpdateTime(LocalDateTime.now());
            cpsSearchHistory.setUpdateTime(LocalDateTime.now());
            boolean b=cpsSearchHistoryService.ownSave( cpsSearchHistory);
            if(!b){
                return  error("增加历史搜索失败");
            }
        }
        QueryWrapper<CpsHotSearch> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("status", Constants.STATUS_NORMAL);
        queryWrapper1.eq("title",vo.getTitle());
        List<CpsHotSearch>  cpsHotSearches=cpsHotSearchService.list(queryWrapper1);
        if (cpsHotSearches.size()>0){
            CpsHotSearch cpsHotSearch =cpsHotSearches.get(0);
            Long pv=cpsHotSearch.getPv();
            cpsHotSearch.setPv(pv++);
            boolean b1=cpsHotSearchService.ownUpdateById(cpsHotSearch);
            if(!b1){
                return  error("增加热门搜索失败");
            }
        }else {
            CpsHotSearch cpsHotSearch = new CpsHotSearch();
            cpsHotSearch.setId(IdWorker.getId());
            cpsHotSearch.setPv(1L);
            cpsHotSearch.setStatus(Constants.STATUS_CREDIT);
            cpsHotSearch.setTitle(vo.getTitle());
            cpsHotSearch.setCreateTime(LocalDateTime.now());
            cpsHotSearch.setUpdateTime(LocalDateTime.now());
            boolean b1=cpsHotSearchService.ownSave(cpsHotSearch);
            if(!b1){
                return  error("增加热门搜索失败");
            }
        }
        return error();
    }
}
